<template>
  <div class="register-container">
    <el-card class="register-card">
      <div class="header">
        <h2>用户注册</h2>
        <p>创建您的账号</p>
      </div>
      
      <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-position="top">
        <el-form-item prop="role" label="用户类型">
          <el-select v-model="registerForm.role" placeholder="请选择用户类型" class="form-input" @change="handleRoleChange">
            <el-option label="患者" value="patient"></el-option>
            <el-option label="医生" value="doctor"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item prop="id" label="账号">
          <el-input v-model="registerForm.id" placeholder="请输入账号" class="form-input"></el-input>
        </el-form-item>
        
        <el-form-item prop="password" label="密码">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" class="form-input"></el-input>
        </el-form-item>
        
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" class="form-input"></el-input>
        </el-form-item>
        
        <el-form-item prop="name" label="姓名">
          <el-input v-model="registerForm.name" placeholder="请输入姓名" class="form-input"></el-input>
        </el-form-item>
        
        <el-form-item prop="gender" label="性别">
          <el-radio-group v-model="registerForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item prop="phone" label="手机号码">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号码" class="form-input"></el-input>
        </el-form-item>
        
        <el-form-item prop="card" label="证件号码">
          <el-input v-model="registerForm.card" placeholder="请输入身份证号码" class="form-input"></el-input>
        </el-form-item>
        
        <el-form-item prop="email" label="电子邮箱">
          <el-input v-model="registerForm.email" placeholder="请输入电子邮箱" class="form-input"></el-input>
        </el-form-item>
        
        <!-- 患者特有字段 -->
        <template v-if="registerForm.role === 'patient'">
          <el-form-item prop="birthday" label="出生日期">
            <el-date-picker v-model="registerForm.birthday" type="date" placeholder="选择出生日期" class="form-input" @change="calculateAge"></el-date-picker>
          </el-form-item>
          
          <el-form-item prop="age" label="年龄">
            <el-input v-model="registerForm.age" placeholder="年龄将根据出生日期自动计算" class="form-input" disabled></el-input>
          </el-form-item>
        </template>
        
        <!-- 医生特有字段 -->
        <template v-if="registerForm.role === 'doctor'">
          <el-form-item prop="post" label="职称">
            <el-select v-model="registerForm.post" placeholder="请选择职称" class="form-input">
              <el-option label="主任医师" value="主任医师"></el-option>
              <el-option label="副主任医师" value="副主任医师"></el-option>
              <el-option label="主治医师" value="主治医师"></el-option>
              <el-option label="住院医师" value="住院医师"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item prop="introduction" label="个人简介">
            <el-input v-model="registerForm.introduction" type="textarea" rows="3" placeholder="请输入个人简介" class="form-input"></el-input>
          </el-form-item>
          
          <el-form-item prop="section" label="科室">
            <el-select v-model="registerForm.section" placeholder="请选择科室" class="form-input">
              <el-option label="内科" value="内科"></el-option>
              <el-option label="外科" value="外科"></el-option>
              <el-option label="妇产科" value="妇产科"></el-option>
              <el-option label="儿科" value="儿科"></el-option>
              <el-option label="骨科" value="骨科"></el-option>
              <el-option label="神经科" value="神经科"></el-option>
              <el-option label="精神科" value="精神科"></el-option>
              <el-option label="眼科" value="眼科"></el-option>
              <el-option label="耳鼻喉科" value="耳鼻喉科"></el-option>
              <el-option label="口腔科" value="口腔科"></el-option>
              <el-option label="皮肤科" value="皮肤科"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item prop="price" label="挂号费">
            <el-input-number v-model="registerForm.price" :min="0" :precision="2" :step="10" class="form-input"></el-input-number>
          </el-form-item>
        </template>
        
        <div class="form-actions">
          <el-button type="primary" :loading="loading" @click="handleRegister" class="register-btn">注册</el-button>
        </div>
        
        <div class="form-links">
          <span>已有账号? <router-link to="/login">去登录</router-link></span>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useAuthStore } from '../../stores/auth'
import { ElMessage } from 'element-plus'

const authStore = useAuthStore()
const loading = ref(false)
const registerFormRef = ref(null)

const registerForm = reactive({
  role: 'patient',
  id: '',
  password: '',
  confirmPassword: '',
  name: '',
  gender: 'male',
  phone: '',
  card: '',
  email: '',
  // 患者特有字段
  birthday: '',
  age: '',
  // 医生特有字段
  post: '',
  introduction: '',
  section: '',
  price: 50
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validateConfirmPass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  role: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
  id: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
  confirmPassword: [{ validator: validateConfirmPass, trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  card: [
    { required: true, message: '请输入证件号码', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  // 患者特有规则
  birthday: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  // 医生特有规则
  post: [{ required: true, message: '请选择职称', trigger: 'change' }],
  section: [{ required: true, message: '请选择科室', trigger: 'change' }],
  price: [{ required: true, message: '请设置挂号费', trigger: 'blur' }]
}

const calculateAge = () => {
  if (!registerForm.birthday) return
  
  const birthDate = new Date(registerForm.birthday)
  const today = new Date()
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  
  registerForm.age = age
}

const handleRoleChange = () => {
  // Reset role-specific fields when role changes
  if (registerForm.role === 'patient') {
    registerForm.post = ''
    registerForm.introduction = ''
    registerForm.section = ''
    registerForm.price = 50
  } else {
    registerForm.birthday = ''
    registerForm.age = ''
  }
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    // Format birthday to string if it's a Date object
    if (registerForm.birthday instanceof Date) {
      registerForm.birthday = registerForm.birthday.toISOString().split('T')[0]
    }
    
    await authStore.register(registerForm)
    
    if (authStore.error) {
      ElMessage.error(authStore.error)
    } else {
      ElMessage.success('注册成功，请登录')
    }
  } catch (validationError) {
    console.error('Validation error:', validationError)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px 0;
  background-color: #f5f7fa;
}

.register-card {
  width: 500px;
  max-width: 100%;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.header p {
  color: #909399;
  font-size: 14px;
}

.form-input {
  width: 100%;
}

.form-actions {
  margin-top: 24px;
}

.register-btn {
  width: 100%;
}

.form-links {
  margin-top: 16px;
  text-align: center;
  font-size: 14px;
}

.form-links a {
  color: #409eff;
  text-decoration: none;
}
</style> 